<template>
  <div class="chat-sidebar">
    <div class="sidebar-header">
      <el-button 
        type="primary" 
        :icon="Plus" 
        @click="createNewChat"
        class="new-chat-btn"
      >
        新建对话
      </el-button>
    </div>
    
    <div class="chat-list">
      <div class="section-title">
        <span>最近对话</span>
        <el-button 
          type="text" 
          size="small" 
          :icon="Refresh" 
          @click="refreshChats"
          :loading="loading"
        />
      </div>
      
      <div class="chat-items">
        <div
          v-for="session in sessions"
          :key="session.id"
          class="chat-item"
          :class="{ active: currentSessionId === session.id }"
          @click="selectChat(session.id)"
        >
          <div class="chat-content">
            <div class="chat-title">
              <el-icon><ChatDotRound /></el-icon>
              <span class="title-text">{{ session.title }}</span>
            </div>
            <div class="chat-preview">
              {{ getLastMessage(session) }}
            </div>
            <div class="chat-meta">
              <span class="time">{{ formatTime(session.updatedAt) }}</span>
              <span class="message-count">{{ session.messages.length }} 条消息</span>
            </div>
          </div>
          
          <div class="chat-actions">
            <el-dropdown trigger="click" @command="handleCommand">
              <el-button type="text" :icon="MoreFilled" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item :command="{ action: 'rename', id: session.id }">
                    <el-icon><Edit /></el-icon>
                    重命名
                  </el-dropdown-item>
                  <el-dropdown-item :command="{ action: 'export', id: session.id }">
                    <el-icon><Download /></el-icon>
                    导出
                  </el-dropdown-item>
                  <el-dropdown-item 
                    :command="{ action: 'delete', id: session.id }"
                    divided
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
      
      <div v-if="sessions.length === 0" class="empty-state">
        <el-empty description="暂无对话记录" :image-size="80">
          <el-button type="primary" @click="createNewChat">
            开始新对话
          </el-button>
        </el-empty>
      </div>
    </div>
    
    <!-- 重命名对话框 -->
    <el-dialog
      v-model="renameDialogVisible"
      title="重命名对话"
      width="400px"
    >
      <el-input
        v-model="newTitle"
        placeholder="请输入新的对话标题"
        maxlength="50"
        show-word-limit
      />
      <template #footer>
        <el-button @click="renameDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRename">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Refresh,
  ChatDotRound,
  MoreFilled,
  Edit,
  Download,
  Delete
} from '@element-plus/icons-vue'
import { useChatStore } from '@/stores/chat'

interface ChatSession {
  id: string
  title: string
  messages: Array<{
    id: string
    role: 'user' | 'assistant'
    content: string
    timestamp: Date
  }>
  createdAt: Date
  updatedAt: Date
}

const chatStore = useChatStore()

const loading = ref(false)
const renameDialogVisible = ref(false)
const newTitle = ref('')
const selectedSessionId = ref('')

const sessions = computed(() => chatStore.sessions)
const currentSessionId = computed(() => chatStore.currentSession?.id || '')

// 创建新对话
const createNewChat = () => {
  chatStore.createSession()
  ElMessage.success('已创建新对话')
}

// 选择对话
const selectChat = (sessionId: string) => {
  chatStore.selectSession(sessionId)
}

// 刷新对话列表
const refreshChats = async () => {
  loading.value = true
  try {
    // 这里可以添加从服务器刷新数据的逻辑
    await new Promise(resolve => setTimeout(resolve, 500))
    ElMessage.success('对话列表已刷新')
  } catch (error) {
    ElMessage.error('刷新失败')
  } finally {
    loading.value = false
  }
}

// 获取最后一条消息
const getLastMessage = (session: ChatSession) => {
  const lastMessage = session.messages[session.messages.length - 1]
  if (!lastMessage) return '暂无消息'
  
  const content = lastMessage.content
  return content.length > 30 ? content.substring(0, 30) + '...' : content
}

// 格式化时间
const formatTime = (timestamp: Date) => {
  const now = new Date()
  const diff = now.getTime() - timestamp.getTime()
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return timestamp.toLocaleDateString('zh-CN')
}

// 处理下拉菜单命令
const handleCommand = (command: { action: string; id: string }) => {
  const { action, id } = command
  
  switch (action) {
    case 'rename':
      showRenameDialog(id)
      break
    case 'export':
      exportChat(id)
      break
    case 'delete':
      deleteChat(id)
      break
  }
}

// 显示重命名对话框
const showRenameDialog = (sessionId: string) => {
  const session = sessions.value.find(s => s.id === sessionId)
  if (session) {
    selectedSessionId.value = sessionId
    newTitle.value = session.title
    renameDialogVisible.value = true
  }
}

// 确认重命名
const confirmRename = () => {
  if (newTitle.value.trim()) {
    chatStore.updateSessionTitle(selectedSessionId.value, newTitle.value.trim())
    renameDialogVisible.value = false
    ElMessage.success('重命名成功')
  }
}

// 导出对话
const exportChat = (sessionId: string) => {
  const session = sessions.value.find(s => s.id === sessionId)
  if (session) {
    const content = JSON.stringify(session, null, 2)
    const blob = new Blob([content], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `chat_${session.id}_${session.title}.json`
    a.click()
    URL.revokeObjectURL(url)
    ElMessage.success('对话已导出')
  }
}

// 删除对话
const deleteChat = async (sessionId: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个对话吗？此操作不可恢复！',
      '确认删除',
      {
        type: 'warning',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      }
    )
    
    chatStore.deleteSession(sessionId)
    ElMessage.success('对话已删除')
  } catch {
    // 用户取消删除
  }
}
</script>

<style scoped>
.chat-sidebar {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fafafa;
  border-right: 1px solid #e4e7ed;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #e4e7ed;
}

.new-chat-btn {
  width: 100%;
  height: 40px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  font-weight: 600;
}

.new-chat-btn:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.chat-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
  font-weight: 600;
  color: #606266;
}

.chat-items {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
}

.chat-item:hover {
  background: #f8f9fa;
  border-color: #e4e7ed;
}

.chat-item.active {
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1) 0%, rgba(118, 75, 162, 0.1) 100%);
  border-color: #667eea;
}

.chat-content {
  flex: 1;
  min-width: 0;
}

.chat-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.chat-title .el-icon {
  color: #667eea;
  font-size: 16px;
}

.title-text {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-preview {
  color: #909399;
  font-size: 12px;
  line-height: 1.4;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.chat-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 11px;
  color: #c0c4cc;
}

.chat-actions {
  margin-left: 8px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.chat-item:hover .chat-actions {
  opacity: 1;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

@media (max-width: 768px) {
  .chat-sidebar {
    position: fixed;
    left: -280px;
    top: 0;
    width: 280px;
    height: 100vh;
    z-index: 1000;
    transition: left 0.3s ease;
  }
  
  .chat-sidebar.mobile-open {
    left: 0;
  }
}
</style>